import React, {useState, useRef} from 'react';
import {View, TouchableOpacity, Text, StyleSheet, Image} from 'react-native';
import {RNCamera} from 'react-native-camera';
import Video from 'react-native-video';
import {CameraRoll} from '@react-native-camera-roll/camera-roll';

const CameraDemo = () => {
  const [photoUri, setPhotoUri] = useState<string>('');
  const [videoUri, setVideoUri] = useState<string>('');
  const [isRecording, setIsRecording] = useState<boolean>(false);
  const cameraRef = useRef<RNCamera>(null);

  const takePicture = async () => {
    onReset();
    const options = {quality: 0.5, base64: true};
    const data = (await cameraRef.current?.takePictureAsync(options)) as any;
    setPhotoUri(data?.uri);
  };

  const startRecording = async () => {
    onReset();
    const videoOptions = {
      maxDuration: 10,
      mute: false,
      quality: RNCamera.Constants.VideoQuality['720p'],
    };
    setIsRecording(true);
    const data = (await cameraRef.current?.recordAsync(videoOptions)) as any;
    setVideoUri(data.uri);
    setIsRecording(false);
  };

  const stopRecording = () => {
    cameraRef.current?.stopRecording();
    setIsRecording(false);
    onReset();
  };
  const onReset = () => {
    setPhotoUri('');
    setVideoUri('');
  };
  const onSave = () => {
    let uri = photoUri || videoUri;
    if (uri && uri.match(/^file/)) uri = uri.replace(/file:\/\//, '');
    CameraRoll.saveAsset(uri).then(() => {
      let timer = setTimeout(() => {
        onReset();
        clearTimeout(timer);
      }, 500);
    });
  };

  return (
    <View style={styles.container}>
      {photoUri || videoUri ? (
        <>
          {photoUri ? (
            <Image source={{uri: photoUri}} style={styles.camera} />
          ) : null}
          {videoUri ? (
            <Video source={{uri: videoUri}} style={styles.camera} controls />
          ) : null}
        </>
      ) : (
        <RNCamera
          ref={cameraRef}
          style={styles.camera}
          type={RNCamera.Constants.Type.back}
          flashMode={RNCamera.Constants.FlashMode.off}
          useNativeZoom
          pictureSize="1280x720"
        />
      )}
      <View style={styles.buttonContainer}>
        {photoUri || videoUri ? (
          <>
            <TouchableOpacity style={styles.button} onPress={onSave}>
              <Text>save</Text>
            </TouchableOpacity>{' '}
            <TouchableOpacity style={styles.button} onPress={onReset}>
              <Text>reset</Text>
            </TouchableOpacity>
          </>
        ) : (
          <>
            <TouchableOpacity style={styles.button} onPress={takePicture}>
              <Text>拍照</Text>
            </TouchableOpacity>

            {isRecording ? (
              <TouchableOpacity
                style={[styles.button, styles.redButton]}
                onPress={stopRecording}>
                <Text>停止录制</Text>
              </TouchableOpacity>
            ) : (
              <TouchableOpacity style={styles.button} onPress={startRecording}>
                <Text>开始录制</Text>
              </TouchableOpacity>
            )}
          </>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  camera: {
    height: '80%',
  },
  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-around',
    margin: 20,
  },
  button: {
    flex: 1,
    padding: 10,
    backgroundColor: '#fff',
    borderRadius: 5,
    marginHorizontal: 5,
    justifyContent: 'center',
    alignItems: 'center',
  },
  redButton: {
    backgroundColor: 'red',
  },
});

export default CameraDemo;
